<script setup lang="ts">
import { createMedicineOrderService, getAddressListService, getMedicalOrderPreService } from '@/api/medicine'
import type { OrderPre, AddressItem } from '@/types/medicine'
import { Toast } from 'vant'
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMedicineStore } from '@/stores'

const route = useRoute()
// 1. 订单预支付信息
const orderPre = ref<OrderPre>()
const getOrderPre = async () => {
  const res = await getMedicalOrderPreService({ prescriptionId: route.query.id as string })
  console.log(res)
  orderPre.value = res
}

// 2. 地址列表
const medicineStore = useMedicineStore()
const defaultAddress = ref<AddressItem>()
const getAddress = async () => {
  const res = await getAddressListService()
  let address
  if(medicineStore.choosedAddressId) {
     address = res.find((item) => item.id === medicineStore.choosedAddressId)
     medicineStore.chooseAddress('') // 清空
  } else {
     address = res.find((item) => item.isDefault === 1)
  }
  if (address) {
    defaultAddress.value = address
  }
}

onMounted(() => {
  getAddress()
  getOrderPre()
})

// 3. 支付协议
const isAgree = ref(false)
const show = ref(false)
const orderId = ref('')
const loading = ref(false)
const handleSubmit = async  () => {
  
  if(!defaultAddress.value) {
    return Toast('请先选择收货地址')
  }
  if (!isAgree.value) {
    return Toast.fail('请先同意支付协议')
  }
  try {
    loading.value = true
  // 5.生成订单
    const res = await createMedicineOrderService({id: route.query.id as string,addressId: defaultAddress.value!.id!})
    orderId.value = res.id
    show.value = true
  } catch (error) {
    
  }finally {
    loading.value = false
  }


}

// 4. 选择地址
const router = useRouter()
const chooseAddress = () => {
  router.push('/user/address?isChange=1')
}

// 支付回调地址
const payCallback = import.meta.env.DEV
          ? 'http://localhost:5173/#/medicine/pay/result'
          : 'https://ljh-online-consult.netlify.app/#/medicine/pay/result'
</script>

<template>
  <div class="order-pay-page" v-if="orderPre">
    <cp-nav-bar title="药品支付" />
    <div class="order-address" v-if="defaultAddress" @click="chooseAddress">
      <p class="area">
        <van-icon name="location" />
        <span>{{defaultAddress.province}} {{defaultAddress.city}} {{defaultAddress.county || ''}} </span>
      </p>
      <p class="detail">{{defaultAddress.addressDetail}}</p>
      <p>{{defaultAddress.receiver}} {{defaultAddress.mobile}}</p>
      <div class="arrow">
        <cp-icon name="home-arrow-right"></cp-icon>
      </div>
    </div>
    <div class="order-address" v-else @click="chooseAddress">
      <p class="choose-address area">
        <div><van-icon name="location" size="large"/>
          <span>请选择地址</span></div>
        <cp-icon name="home-arrow-right"></cp-icon>
      </p>
    </div>
    <div class="order-medical">
      <div class="smalld">
        <h3>优医药房</h3>
        <small>优医质保 假一赔十</small>
      </div>
      <div class="item van-hairline--top" v-for="i in orderPre?.medicines" :key="i.id">
        <img class="img" :src="i.avatar" alt="图片加载失败" />
        <div class="info">
          <p class="name">
            <span>{{ i.name }}</span
            ><span>x{{ i.quantity }}</span>
          </p>
          <p class="size">
            <van-tag>{{ i.prescriptionFlag === 1 ? '处方药' : '非处方药' }}</van-tag>
            <span>{{ i.specs }}</span>
          </p>
          <p class="price">￥{{ i.amount }}</p>
        </div>
        <div class="desc">{{ i.usageDosag }}</div>
      </div>
    </div>
    <div class="order-detail">
      <van-cell-group
        ><van-cell title="药品金额" :value="`￥${orderPre?.payment || 0}`" />
        <van-cell title="运费" :value="`￥${orderPre?.expressFee || 0}`" />
        <van-cell title="优惠券" :value="`-￥${orderPre?.couponDeduction || 0}`" />
        <van-cell title="实付款" :value="`￥${orderPre?.actualPayment || 0}`" class="price" />
      </van-cell-group>
    </div>
    <div class="order-tip">
      <p class="tip">
        由于药品的特殊性，如非错发、漏发药品的情况，药品一经发出
        不得退换，请核对药品信息无误后下单。
      </p>
      <van-checkbox v-model="isAgree">我已同意<a href="javascript:;">支付协议</a></van-checkbox>
    </div>
    <van-submit-bar
      :price="orderPre?.actualPayment ? orderPre.actualPayment * 100 : 0"
      :loading="loading"
      button-text="立即支付"
      button-type="primary"
      text-align="left"
      @submit="handleSubmit"
    ></van-submit-bar>
    <!-- 支付弹层 -->
    <cp-pay-sheet
      :order-id="orderId"
      v-model:show="show"
      :actual-payment="orderPre.actualPayment"
      :pay-callback="
        payCallback
      "
    >
    </cp-pay-sheet>
  </div>
  <!-- 骨架屏 -->
  <div class="order-pay-page" v-else>
    <cp-nav-bar title="药品支付"></cp-nav-bar>
    <van-skeleton class="vsk" :row="3" title></van-skeleton>
    <van-skeleton class="vsk" :row="3" title></van-skeleton>
    <van-skeleton class="vsk" :row="12" title></van-skeleton>
  </div>
</template>

<style lang="scss" scoped>
:deep(.van-nav-bar) {
  background-color: var(--cp-primary);
  .van-nav-bar__arrow,
  .van-nav-bar__title {
    color: #fff;
  }
}
:deep(.van-cell) {
  .van-cell__title {
    font-size: 16px;
  }
  .van-cell__value {
    font-size: 16px;
  }
  &.price {
    .van-cell__value {
      font-size: 18px;
      color: var(--cp-price);
    }
  }
}
:deep(.van-submit-bar) {
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.1);
  .van-button {
    width: 200px;
  }
}
.order-pay-page {
  padding: 46px 0 65px;
  .vsk {
    margin-bottom: 20px;
  }
}
.order-address {
  position: relative;
  padding: 15px 15px 0 15px;
  background-color: #fff;
  font-size: 13px;
  &:active {
    background-color: var(--cp-bg);
  }
  .choose-address {
    display: flex;
    justify-content: space-between;
    font-size: 16px;
    .icon {
      width: 25px;
      height: 25px;
    }
  }
  .area {
    color: var(--cp-tag);
    margin-bottom: 5px;
    .van-icon-location {
      color: #ff7702;
      font-size: 14px;
    }
  }
  .detail {
    font-size: 17px;
    margin-bottom: 5px;
  }
  .arrow {
    position: absolute;
    right: 15px;
    top: 35px;
    .icon {
      width: 32px;
      height: 32px;
    }
  }
  &::after {
    content: '';
    display: block;
    height: 12px;
    background-color: var(--cp-bg);
    margin: 0 -15px;
    margin-top: 15px;
  }
}

.order-medical {
  background-color: #fff;
  padding: 0 15px;
  .head {
    display: flex;
    height: 54px;
    align-items: center;
    > h3 {
      font-size: 16px;
      font-weight: normal;
    }
    > small {
      font-size: 13px;
      color: var(--cp-tag);
      margin-left: 10px;
    }
  }
  .item {
    display: flex;
    flex-wrap: wrap;
    padding: 15px 0;
    .img {
      width: 80px;
      height: 70px;
      border-radius: 2px;
      overflow: hidden;
    }
    .info {
      padding-left: 15px;
      width: 250px;
      .name {
        display: flex;
        font-size: 15px;
        margin-bottom: 5px;
        > span:first-child {
          width: 200px;
        }
        > span:last-child {
          width: 50px;
          text-align: right;
        }
      }
      .size {
        margin-bottom: 5px;
        .van-tag {
          background-color: var(--cp-primary);
          vertical-align: middle;
        }
        span:not(.van-tag) {
          margin-left: 10px;
          color: var(--cp-tag);
          vertical-align: middle;
        }
      }
      .price {
        font-size: 16px;
        color: #eb5757;
      }
    }
    .desc {
      width: 100%;
      background-color: var(--cp-bg);
      border-radius: 4px;
      margin-top: 10px;
      padding: 4px 10px;
      color: var(--cp-tip);
    }
  }
}
.order-tip {
  padding: 0 15px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 10px;
  .tip {
    font-size: 12px;
    color: var(--cp-tag);
    width: 100%;
    &::before {
      content: '*';
      color: var(--cp-price);
      font-size: 14px;
    }
    margin-bottom: 30px;
  }
  .van-checkbox {
    a {
      color: var(--cp-primary);
    }
  }
}
</style>
